package com.example;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet("/fastJsonServlet03")
public class FastJsonServlet03 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /*public static final <T> T parseObject(InputStream is, Class<T> clazz);
         // 将从页面获取的字节输入流中的字符数据解析成指定类型JavaBean */
        User user=JSON.parseObject(request.getInputStream(),User.class);
        System.out.println(user);

        ArrayList<User> list=new ArrayList<>();
        //将数据批量添加到集合中
        Collections.addAll(list,new User(1,"ss",20),new User(2,"qq",18),new User(3,"tt",22));
        //JSON.toJSONString()将集合转换为字符串
        String str= JSON.toJSONString(list);

        //响应数据
        response.getWriter().print(str);
    }
}